import { App } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';

import sharelink from '@/api/services/sharelink';
import { Alert, Button, CopyLabel, Tags } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';
import { useConfirm } from '@/hooks/use-confirm';
import { useRequest2 } from '@/hooks/use-request';
import { useParams } from '@/router/hooks';
import { Channel, ChannelBase, ChannelType } from '@/types/share-link';

import { ViewAddressModal } from '../../components/ViewAddressModal';
import { TagRender } from '../utils';

import NewApiKeyModal from './componnets/NewApiKeyModal';

const Api = () => {
  const { message } = App.useApp();
  const [newApiKeyModalOpen, setNewApiKeyModalOpen] = useState(false);
  const [viewAddressModalOpen, setViewAddressModalOpen] = useState(false);
  const [editValue, setEditValue] = useState<ChannelBase | undefined>(undefined);
  const [viewAddress, setViewAddress] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const msg = (
    <p>
      通过建立API可将该应用接入已有的系统中，具体使用方式请
      <a
        href="https://eai.ruijie.com.cn/docs/channel/apikey"
        target="_blank"
        rel="noreferrer"
        style={{ textDecoration: 'underline' }}
      >
        查看文档
      </a>
    </p>
  );

  const { openConfirm, ConfirmModal } = useConfirm({
    type: 'delete',
  });

  const { appId = '' } = useParams() as {
    appId: string;
  };

  const {
    data: channels,
    refresh,
    loading,
  } = useRequest2(
    () => sharelink.getChannelList({ appId, page, pageSize, type: ChannelType.apikey }),
    {
      manual: false,
      refreshDeps: [appId, page, pageSize],
      onSuccess: (res) => {
        setTotal(res.total);
      },
    },
  );

  const paginationConfig = {
    current: page,
    pageSize,
    pageSizeOptions: undefined,
    total,
    onChange: (page: number, pageSize: number) => {
      setPage(page);
      setPageSize(pageSize);
    },
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (name: string) => {
        return <div className="w-[250px] truncate">{name}</div>;
      },
    },
    {
      title: 'API KEY',
      dataIndex: 'apiKey',
    },
    {
      title: '知识库',
      dataIndex: 'permissions',
      render: (permissions: any) => {
        const options = permissions.map((permission: any) => ({
          label: permission.resource_name,
          value: permission.resource_id,
        }));
        const value = permissions.map((permission: any) => ({
          label: permission.resource_name,
          value: permission.resource_id,
        }));
        return (
          <Tags
            className="w-[1/2] truncate"
            options={options}
            value={value}
            tagRender={TagRender}
          />
        );
      },
    },
    {
      title: '过期时间',
      width: 180,
      dataIndex: 'limit',
      render: (limit: any) => {
        return limit.expiredTime ? dayjs(limit.expiredTime).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '创建时间',
      width: 180,
      dataIndex: 'createTime',
      render: (createTime: any) => {
        return createTime ? dayjs(createTime).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      render: (_: unknown, record: Channel) => {
        return (
          <div className="flex items-center gap-2">
            <Button
              type="link"
              icon={<SvgIcon className="-mr-1 mb-1" icon="edit" color="var(--brand-color)" />}
              onClick={() => {
                const c = {
                  ...record,
                  datasets: record.permissions.map((permission: any) => ({
                    key: permission.resource_id,
                    title: permission.resource_name,
                    type: permission.resource_type,
                  })),
                };
                setEditValue(c);
                setNewApiKeyModalOpen(true);
              }}
            >
              编辑
            </Button>
            <Button
              type="link"
              danger
              icon={
                <SvgIcon className="-mr-1 mb-1" icon="delete-icons" color="var(--error-color)" />
              }
              onClick={() => {
                openConfirm(
                  async () => {
                    await sharelink.deleteChannel(record.id ?? '');
                    message.success('删除成功');
                    refresh();
                  },
                  undefined,
                  `确认删除API【${record.name}】, 删除后使用该API的服务会立即失效?`,
                )();
              }}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <div className="relative flex h-full flex-col overflow-hidden">
      <PagesHeader>API访问</PagesHeader>
      <div className="relative mt-4 flex flex-1 flex-col gap-4 px-5">
        <Alert message={msg} type="info" />
        <div className="flex w-2/5 flex-col gap-2">
          <span className="text-cn-14 text-text-4">API地址</span>
          <CopyLabel text={`${window.location.origin}/api/v1`} />
        </div>
        <div className="flex justify-between gap-2">
          <div className="flex flex-col">
            <span className="text-cn-16 font-font-weight-600 text-text-5 ">API秘钥管理</span>
            <span className="text-cn-12 text-text-5">这些 key 已有当前应用标识</span>
          </div>
          <Button
            type="secondary"
            icon={<SvgIcon className="-mr-1 mb-[3px]" icon="add" size={16} />}
            onClick={() => setNewApiKeyModalOpen(true)}
          >
            创建秘钥
          </Button>
        </div>

        <div className="flex-1">
          <Tables<Channel>
            rowKey="id"
            columns={columns}
            dataSource={channels?.list ?? []}
            loading={loading}
            paginationProps={paginationConfig}
          />
        </div>
      </div>
      <NewApiKeyModal
        channel={editValue as any}
        open={newApiKeyModalOpen}
        onCancel={() => {
          setEditValue(undefined);
          setNewApiKeyModalOpen(false);
        }}
        onApiKeyCreated={(apiKey) => {
          setViewAddress(apiKey);
          setViewAddressModalOpen(true);
        }}
        onRefresh={refresh}
      />
      <ViewAddressModal
        open={viewAddressModalOpen}
        onCancel={() => setViewAddressModalOpen(false)}
        url={viewAddress}
        title="新的密钥"
        header={
          <div className="mb-4">
            <Alert
              message={
                <div className="flex items-center gap-2">
                  <SvgIcon icon="warning" />
                  请保管好密钥，密钥不会再次展示
                </div>
              }
              type="warning"
            />
          </div>
        }
      />
      <ConfirmModal />
    </div>
  );
};

export default Api;
